
import React from 'react'
import ReactDOM from 'react-dom'
import * as UnitAction  from '../../actions/UnitAction';
import * as AssetAction  from '../../actions/AssetAction';
import { connect }  from 'react-redux';
import Paging from '../Paging'
import _ from 'lodash'


class UnitBindList extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      data: {},
      sys_user_id: '',
      bindIds: []
    }
  }

  componentDidMount() {
    this.props.dispatch(
      UnitAction.loadUsersAsync(this.props.sysuser)
    )

    this.props.dispatch(
      UnitAction.loadSysUserUnitsLimitAsync({
        limit: 6
      })
    )

  }

  componentWillReceiveProps(props) {
    this.setState({
      data: props.data
    })
  }

  onDataSubmit() {
    var sys_user_id = this.state.sys_user_id;
    var _bindIds = this.state.bindIds;
    console.log("sys_user_id" + sys_user_id);
    if (!sys_user_id || sys_user_id == '' || sys_user_id == '选择管家客服') {
      alert("请先选择管家客服");
      return;
    }else{
      this.props.onSysUserUpdate({
        sys_user_id: sys_user_id,
        unit_ids: _bindIds
      })
    }

    this.setState({
      sys_user_id: '',
      bindIds: []
    })

    $(ReactDOM.findDOMNode(this.refs.userDrop)).html("选择管家客服")
    this.props.dispatch(
      UnitAction.loadUsersAsync({})
    )
  }

  onDataCancel(){
    this.setState({
      bindIds: []
    })
    $(ReactDOM.findDOMNode(this.refs.userDrop)).html("选择管家客服")
  }

  onChange(event, key) {
    var value = $(event.target).val();
    var data = this.state.data;
    data[key] = value;
    this.setState({
      data: data
    })
  }

  onPageChange(page) {
    var self = this;
    this.props.dispatch(
      UnitAction.loadSysUserUnitsLimitAsync({
        offset: (page-1)*this.props.limit,
        limit: self.props.limit
      })
    )
  }

  //选择物业管家
  onUserFileterClick(data){

    var userName = data?data.lastName + ' ' + data.firstName:"选择管家客服" ;
    var sysUserId = data?data.id:"";
    $(ReactDOM.findDOMNode(this.refs.userDrop)).html(userName.length>0?userName: "选择管家客服" )
    if (data) {
      var bindIds = [];
      data.unit.forEach(function(unit) {
        bindIds.push(unit.id)
      })
      this.setState({
        sys_user_id: sysUserId,
        bindIds: bindIds
      })
    }
  }

  onCheckClick(event, data) {
    var bindIds = this.state.bindIds;
    var hasOne = _.find(bindIds, function(id) {
      return data.id == id
    })

    if (hasOne) {
      //删
      _.remove(bindIds, function(id) {
        return data.id == id
      })
      this.setState({
        bindIds: bindIds
      })
    }
    else {
      //加

      bindIds.push(data.id)
      this.setState({
        bindIds: bindIds
      })
    }
  }

  renderSysList() {
    var self = this;
    var content = [];
    if (this.props.users_data && this.props.users_data.length > 0) {
      // console.log(this.props.users_data)
      var _data = this.props.users_data;
      _data.forEach(function(data, index) {
        content.push((
            <li onClick={(event)=> self.onUserFileterClick(data)}>{data.lastName + ' ' + data.firstName}</li>
        ))
      })

    }
    return content
  }

  renderList() {
    var self = this;
    var content = [];
    var _data = this.props.data

    // console.log(_data);
    if (this.props.data && this.props.data.length > 0) {
      this.props.data.forEach(function(data, index) {
        var property = data.property
        var hasOne = _.find(self.state.bindIds, function(id) {
          return data.id == id;
        })
        content.push((
          <tr>
            <td>
                {
                  hasOne?<input id={data.id} type="checkbox" aria-label="..." onClick={(event)=>self.onCheckClick(event, data)} checked='checked'/>
                  :
                  <input id={data.id} type="checkbox" aria-label="..." onClick={(event)=>self.onCheckClick(event, data)}/>
                }
            </td>
            <td>{data.unit_number}</td>
            <td>{data.unit_desc}</td>
            <td>{property?property.name:""}</td>
            <td>{data.sys_user?data.sys_user.firstName+" "+data.sys_user.lastName: ""}</td>

          </tr>
        ))
      })
    }

    return content
  }


  render() {
    var self = this;
    var sysUserName =  ""

    var offset = parseInt(this.props.offset),
        limit = parseInt(this.props.limit)

    var current = Math.ceil(offset/limit) + 1;
    var count = this.props.count
    return (
      <div className="modal fade" id="unitSettingEdit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div className="modal-dialog " role="document">
          <div className="modal-content">
            <div className="modal-header">
              <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 className="modal-title" id="unit-modal-label">管家客服绑定</h4>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label for="role-url-permission"></label>
                <div className="dropdown">
                  <button className="btn btn-default dropdown-toggle" type="button" ref="roleUrlPermissionDown"
                          id='role-url-permission-down' data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" >
                    <span ref="userDrop">选择管家客服</span>

                    <span className="caret"></span>
                  </button>
                  <ul ref="roleUrlPermission" id="role-url-permission"  className="dropdown-menu" aria-labelledby="role-url-permission">
                        <li onClick={(event)=> self.onUserFileterClick()}>选择管家客服</li>
                        {this.renderSysList()}
                  </ul>
                </div>
              </div>
              <div className="unit-setting-list unit-bind-list setting-list">
                <table className="table">
                  <thead>
                    <tr className="table-title">
                      <th className="bind">绑定</th>
                      <th className="id">ID</th>
                      <th className="no">户号</th>
                      <th className="name">物业</th>
                      <th className="admin">管家客服</th>
                    </tr>
                  </thead>
                  <tbody>
                    {this.renderList()}
                  </tbody>
                </table>
              </div>
              <div className="modal-paging">
                <Paging
                  current = {current}
                  count = {count}
                  limit = {limit}
                  onPageChange = {this.onPageChange.bind(self)}
                />
              </div>
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-default" data-dismiss="modal"
                      onClick={(event)=> this.onDataCancel()}>取消</button>
              <button type="button" className="btn btn-primary"
                      onClick={(event)=> this.onDataSubmit()}>提交</button>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    data: state.sysUserUnitList.data,
    offset: state.sysUserUnitList.offset,
    limit: state.sysUserUnitList.limit,
    count: state.sysUserUnitList.count,
    users_data: state.sysUserList?state.sysUserList.data:[]
   }
}

export default connect(mapStateToProps)(UnitBindList);
